import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component';
import {TabBarModule} from 'ng-zorro-antd-mobile';
import {HttpClient, HttpClientModule} from '@angular/common/http';
import {GnAppModule, GnHttpInterceptorConfig, GnLoginUser, GnMessageService, GnRouteGuard, GnSiteInfo} from 'geminis-ng-core';
import {addGlobalUncaughtErrorHandler, registerMicroApps, start} from 'qiankun';
import {GnIconServiceModule} from './services/icon-service/icon-service.module';
import {GnMessageServiceModule} from './services/message-service/message-service.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,

    TabBarModule,

    GnIconServiceModule,
    GnMessageServiceModule,
    GnAppModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {

  constructor(private loginUser: GnLoginUser,
              private siteInfo: GnSiteInfo,
              private routeGuard: GnRouteGuard,
              private httpInterceptorConfig: GnHttpInterceptorConfig,
              private messageService: GnMessageService,
              private http: HttpClient) {

    this.loginUser.load();

    this.siteInfo.loginUrl = '/oidc/login';

    this.httpInterceptorConfig.startWithUrl = '/api/';
    this.httpInterceptorConfig.ignoreUrls = ['/api/resources/oauth/token'];

    this.initMicroService();
  }


  private initMicroService(): void {

    addGlobalUncaughtErrorHandler((event: Event | string): void => {
      console.error(event);
      const {message: msg} = event as any;
      // 加载失败时提示
      if (msg && msg.includes('died in status LOADING_SOURCE_CODE')) {
        this.messageService.error('微服务加载失败，请检查应用是否可运行');
      }
    });

    this.http.get('assets/config/services.json')
      .subscribe((services: any) => {
          services.forEach((service: any) => {
            service.props = {
              loginUser: this.loginUser,
              siteInfo: this.siteInfo,
              routeGuard: this.routeGuard,
              httpInterceptorConfig: this.httpInterceptorConfig
            };
          });
          registerMicroApps(
            services,
            {
              // qiankun 生命周期钩子 - 加载前
              beforeLoad: (app: any): Promise<void> => {
                console.log('before load', app.name);
                return Promise.resolve();
              },
              // qiankun 生命周期钩子 - 挂载后
              afterMount: (app: any): Promise<void> => {
                console.log('after mount', app.name);
                return Promise.resolve();
              },
            },
          );

          start({
            prefetch: false
          });
        },
        error => {
          this.messageService.error('获取微服务配置失败');
          console.error(error);
        });
  }

}
